<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class Comments extends Model{
	public $table = 'comment';
	//白名单
	protected $fillable = ['news_id','user_name','comment','createtime','state'];
	//有时间字段不自动更新手动更新
	public $timestamps = false;

	public function getComments(){
		$data = $this->select('*')->paginate(5);
		if (!empty($data)) {
			return $data;
		} else {
			return '';
		}
		
	}

	//id查询
	public function getCommentsById($id=0){
		$data = $this->where('id',$id)->first();
		if (!empty($data)) {
			return $data;
		} else {
			return [];
		}
	}

	//根据News_id查询所有关于本新闻的评论
	public function getCommentsByNews_id($news_id=0){
		$comments = $this->where('news_id',$news_id)->get();
		if (!empty($comments)) {
			return $comments;
		} else {
			return [];
		}
	}

	//根据id更新状态
	public function updateState($id=0,$state=1){
		
		return $this->where('id',$id)->update(['state'=>$state,
			'createtime'=>date('Y-m-d H:i:s',time())]);

	}
	//插入一条数据
	public function insertOne($news_id=0,$name='',$content=''){
		return $this->insert(['news_id'=>$news_id,'user_name'=>$name,
			'comment'=>$content,'pid'=>'0','createtime'=>date('Y-m-d H:i:s',time())]);
	}

	//插如回复评论到comment表内
	public function insertReplay($news_id=0,$name='',$content='',$comment_id=0){
		$data = $this->insert(['news_id'=>$news_id,'user_name'=>$name,
			'comment'=>$content,'pid'=>$comment_id,'path'=>'0,'.$comment_id,
			'createtime'=>date('Y-m-d H:i:s',time())]);
		if(empty($data)){
			return [];
		}else{
			return $data;
		}
	}
	//组装数组  把一级评论和二级评论都组成新的数组 $id_news--新闻id
	public function getList($id_news){
		$list = [];
		$menu = $this->select('*')->where('news_id',$id_news)->where('state','1')->get();
		foreach ($menu as $key => $menu_value) {
			if ($menu_value->pid == 0) {
				//pid 为0 的全部组装成数组
				$list[$menu_value->id] = $menu_value->toArray();
			}else{
				// $list[$menu->column_pid]['list'][$menu->column_id] = $menu->toArray();
				$list[$menu_value->pid]['list'][$menu_value->id] = $menu_value->toArray();
			}	
		}
		return $list;
	}

	//根据评论id查询用户名
	public function getUserNameById($comment_id){
		$res = $this->where('id',$comment_id)->first();
		if(empty($res)){
			return [];
		}else{
			return $res;
		}
	}
	//删除
	public function delOne($id=0){
		return $this->where('id',$id)->delete();
	}
 }














?>